python的imaplib实现搜索邮件

该博客演示了如何利用Python的IMAP4库来统计收件箱和已发送邮件的数量,并读取邮件详细信息。通过登录邮箱并指定查询条件(如发件人或主题),可以实现邮件的检索和计数。示例代码展示了从'ooxx@fuck.com'获取收件箱和已发送邮件的相关数据。
摘要由CSDN通过智能技术生成

废话不说了,也踩了几个坑,直接上代码,后边再研究email模块如何解析邮件

#!/usr/bin/python

import imaplib


# 统计邮件数量的方法
def get_mail_count(mail_data):
    ids = mail_data[0]
    ret = ids.decode('utf-8')
    message_id_list = ret.split()
    return len(message_id_list)


# 读出邮件细节的方法
def get_mail_detail(mail_data):
    msg = mail_data[0]
    msg_list = msg.split()
    print(msg_list)
    for ids in msg_list:
        results, data = imap_object.fetch(ids, "(RFC822)")
        print(data)


imap_user = 'xxoo@fuck.com'
imap_object = imaplib.IMAP4('250.250.250.250', 143)
imap_object.login(imap_user, 'fuck')

imap_object.select('INBOX')  # connect to inbox.
# typ, msg_ids = imap_object.search(None, 'SUBJECT "测试"'.encode('utf-8'))  # 根据主题模糊查询
typ, msg_ids = imap_object.search(None, '(FROM "ooxx@fuck.com")')  # 根据往来联系人
count1 = get_mail_count(msg_ids)
print(count1)
get_mail_detail(msg_ids)

imap_object.select('"Sent Items"')  # connect to Sent Items
# typ2, msg_ids2 = imap_object.search(None, 'SUBJECT "测试"'.encode('utf-8'))  # 根据主题模糊查询
typ2, msg_ids2 = imap_object.search(None, '(TO "ooxx@fuck.com")')  # 根据往来联系人
count2 = get_mail_count(msg_ids2)
print(count2)
get_mail_detail(msg_ids2)

"""
or 或的关系 不加就是 and 中文主题要encode utf-8 有的邮箱可能编码也不好使
status, message = imap_object.search(None, 'OR FROM "ooxx@fuck.com"', 'SUBJECT "测试"'.encode('utf-8'))
"""

imap_object.close()


评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值